from django.contrib import admin
from .models import (
    SparePartCategory, Supplier, SparePart, 
    InventoryRecord, UsageRecord, PurchaseOrder, PurchaseOrderItem
)

class PurchaseOrderItemInline(admin.TabularInline):
    """采购订单项内联"""
    model = PurchaseOrderItem
    extra = 1
    fields = ('spare_part', 'quantity', 'unit_price', 'received_quantity')
    readonly_fields = ('total_price', 'is_fully_received')

class UsageRecordInline(admin.TabularInline):
    """使用记录内联"""
    model = UsageRecord
    extra = 0
    readonly_fields = ('used_at',)
    fields = ('ticket', 'quantity', 'used_by', 'purpose', 'used_at')

class InventoryRecordInline(admin.TabularInline):
    """库存记录内联"""
    model = InventoryRecord
    extra = 0
    readonly_fields = ('operation_date',)
    fields = ('operation_type', 'quantity', 'operator', 'operation_date', 'notes')

@admin.register(SparePartCategory)
class SparePartCategoryAdmin(admin.ModelAdmin):
    """备件分类管理"""
    list_display = ('name', 'parent', 'description')
    list_filter = ('parent',)
    search_fields = ('name', 'description')
    fields = ('name', 'parent', 'description')

@admin.register(Supplier)
class SupplierAdmin(admin.ModelAdmin):
    """供应商管理"""
    list_display = ('name', 'contact_person', 'phone', 'email')
    search_fields = ('name', 'contact_person', 'phone', 'email')
    fieldsets = (
        ('基本信息', {
            'fields': ('name', 'contact_person')
        }),
        ('联系信息', {
            'fields': ('phone', 'email', 'address')
        }),
        ('备注', {
            'fields': ('notes',)
        }),
    )

@admin.register(SparePart)
class SparePartAdmin(admin.ModelAdmin):
    """备件管理"""
    list_display = ('part_number', 'name', 'model', 'category', 'current_stock', 'stock_status', 'status')
    list_filter = ('category', 'status', 'supplier')
    search_fields = ('part_number', 'name', 'model', 'supplier_part_number')
    readonly_fields = ('created_at', 'updated_at', 'current_stock', 'stock_status')
    fieldsets = (
        ('基本信息', {
            'fields': ('part_number', 'name', 'model', 'category', 'status')
        }),
        ('供应商信息', {
            'fields': ('supplier', 'supplier_part_number')
        }),
        ('技术参数', {
            'fields': ('specifications', 'unit', 'unit_price')
        }),
        ('库存管理', {
            'fields': ('min_stock', 'max_stock', 'current_stock', 'stock_status')
        }),
        ('时间信息', {
            'fields': ('created_at', 'updated_at')
        }),
        ('备注', {
            'fields': ('notes',)
        }),
    )
    inlines = [InventoryRecordInline, UsageRecordInline]

    def stock_status(self, obj):
        """库存状态显示"""
        status = obj.stock_status
        if status == 'low':
            return '❌ 库存不足'
        elif status == 'high':
            return '⚠️ 库存过高'
        else:
            return '✅ 正常'
    stock_status.short_description = '库存状态'

@admin.register(InventoryRecord)
class InventoryRecordAdmin(admin.ModelAdmin):
    """库存记录管理"""
    list_display = ('spare_part', 'operation_type', 'quantity', 'operator', 'operation_date')
    list_filter = ('operation_type', 'operation_date')
    search_fields = ('spare_part__name', 'spare_part__part_number', 'operator__username')
    readonly_fields = ('operation_date',)
    date_hierarchy = 'operation_date'

    fieldsets = (
        ('操作信息', {
            'fields': ('spare_part', 'operation_type', 'quantity')
        }),
        ('关联信息', {
            'fields': ('related_order', 'related_usage')
        }),
        ('操作详情', {
            'fields': ('operator', 'operation_date', 'notes')
        }),
    )

@admin.register(UsageRecord)
class UsageRecordAdmin(admin.ModelAdmin):
    """使用记录管理"""
    list_display = ('spare_part', 'quantity', 'used_by', 'ticket', 'used_at')
    list_filter = ('used_at', 'used_by')
    search_fields = ('spare_part__name', 'used_by__username', 'ticket__title')
    readonly_fields = ('used_at',)
    date_hierarchy = 'used_at'

    fieldsets = (
        ('使用信息', {
            'fields': ('spare_part', 'quantity', 'purpose')
        }),
        ('关联信息', {
            'fields': ('ticket', 'used_by')
        }),
        ('时间信息', {
            'fields': ('used_at',)
        }),
    )

@admin.register(PurchaseOrder)
class PurchaseOrderAdmin(admin.ModelAdmin):
    """采购订单管理"""
    list_display = ('order_number', 'supplier', 'status', 'total_amount', 'requested_by', 'created_at')
    list_filter = ('status', 'supplier', 'created_at')
    search_fields = ('order_number', 'supplier__name', 'requested_by__username')
    readonly_fields = ('order_number', 'created_at', 'updated_at', 'approved_at', 'total_amount')
    inlines = [PurchaseOrderItemInline]
    date_hierarchy = 'created_at'

    fieldsets = (
        ('订单信息', {
            'fields': ('order_number', 'supplier', 'status', 'total_amount')
        }),
        ('时间信息', {
            'fields': ('order_date', 'expected_delivery', 'actual_delivery')
        }),
        ('审批信息', {
            'fields': ('requested_by', 'approved_by', 'approved_at')
        }),
        ('时间记录', {
            'fields': ('created_at', 'updated_at')
        }),
        ('备注', {
            'fields': ('notes',)
        }),
    )

    def save_model(self, request, obj, form, change):
        """保存时自动计算总金额"""
        if not obj.requested_by:
            obj.requested_by = request.user
        super().save_model(request, obj, form, change)

@admin.register(PurchaseOrderItem)
class PurchaseOrderItemAdmin(admin.ModelAdmin):
    """采购订单项管理"""
    list_display = ('order', 'spare_part', 'quantity', 'unit_price', 'total_price', 'received_quantity', 'is_fully_received')
    list_filter = ('order__status',)
    search_fields = ('order__order_number', 'spare_part__name')
    readonly_fields = ('total_price', 'is_fully_received')

    fieldsets = (
        ('订单项信息', {
            'fields': ('order', 'spare_part', 'quantity', 'unit_price')
        }),
        ('收货信息', {
            'fields': ('received_quantity',)
        }),
        ('计算信息', {
            'fields': ('total_price', 'is_fully_received')
        }),
    )
